
//
// 130728 - AH - (Created).
//

package org.japril.jutil.pulse;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public final class Products 
{
  private String m_pulseName=null; 
  
  private final Map<String, Set<Product>> m_products=
    new HashMap<String, Set<Product>>();
  
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public Products(){}
  
  /**
   * <p>
   *   Sets name on pulse.
   * </p>
   * @param name Name.
   */
  public void setPulseName(String name){ m_pulseName=name; }
  
  /**
   * <p>
   *   Gets pulse name.
   * </p>
   * @return Name or {@code null} if not named.
   */
  public String getPulseName(){ return m_pulseName; }
  
  /**
   * <p>
   *   Adds 
   *   {@link Product}.
   * </p>
   * @param p {@code Product} to add
   */
  public void addProduct(Product p)
  {
    if (p==null)
    {
      throw new NullPointerException("p");
    }
    
    String type=p.getType();
    Set<Product> s=m_products.get(type);
    if (s==null)
    {
      s=new HashSet<Product>();
      m_products.put(type, s);
    }
    
    s.add(p);
  }
  
  /**
   * <p>
   *   Removes
   *   {@link Product}.
   * </p>
   * @param p {@link Product} to remove.
   * @return {@code true} if removed, {@code false} if not found.
   */
  public boolean removeProduct(Product p)
  {
    if (p==null)
    {
      throw new NullPointerException("p");
    }
    
    String txt=p.getType();
    Set<Product> s=m_products.get(txt);
    return (s==null) ? false : s.remove(p);
  }
  
  /**
   * <p>
   *   Removes products of a given type.
   * </p>
   * @param type Type name.
   * @return {@code true} if any removed, {@code false} if none to remove.
   */
  public boolean removeProducts(String type)
  {
    if (type==null)
    {
      throw new NullPointerException("type");
    }
    
    return m_products.remove(type)!=null;
  }
  
  /**
   * <p>
   *   Removes all 
   *   {@link Product}s.
   * </p>
   */
  public void clear(){ m_products.clear(); }
  
  /**
   * <p>
   *   Tells if is empty.
   * </p>
   * @return {@code true} if is, {@code false} if is not.
   */
  public boolean isEmpty(){ return m_products.isEmpty(); }
  
  /**
   * <p>
   *   Gets number of
   *   {@link Product}s.
   * </p>
   * @return Count.
   */
  public int size(){ return m_products.size(); }
  
  /**
   * <p>
   *   Gets
   *   {@link Product}s of a given type.
   * </p>
   * @param type Type.
   * @return {@link Product}s.
   */
  public Product[] getProducts(String type)
  {
    if (type==null)
    {
      throw new NullPointerException("type");
    }
    
    Set<Product> s=m_products.get(type);
    Product[] retVal=Product.EMPTY_ARRAY;
    return s==null ? retVal : s.toArray(retVal);
  }
  
}
